/**
 * zmn角色模块-角色权限树状列表
 * 文件命名格式：zmn.模块名称.表名称.功能.js
 * @author heguanghua
 * @since 2020/05/12 17:10
 */
// let editObj = null, ptable = null, treeGrid = null, tableId = 'zmn-table', layer = null;
layui.define(['form', 'table', 'zmnApp', 'treeTable2'], function (exports) {
    let $ = layui.jquery;
    let form = layui.form;
    let layer = layui.layer;
    let treeTable = layui.treeTable2;
    let zmnApp = layui.zmnApp;

    var insTb = treeTable.render({
        elem: '#zmn-table',
        toolbar: '#zmn-table-tool',
        defaultToolbar: ['filter', 'print'],
        //url: '/role/permit/ajaxTree.action?roleId=' + json.roleId,
        cellMinWidth: 50,
        height: 'full-196',
        // size: 'sm',
        tree: {
            iconIndex: 2,           // 折叠图标显示在第几列
            isPidData: true,        // 是否是id、pid形式数据
            idName: 'moduleId',     // id字段名称
            pidName: 'parentId'     // pid字段名称
        },
        cols: [[
            {field: '', title: '', width: 50, align: 'center', sort: false, templet: function(d) {
                return d.level > 0 ? '<input type="checkbox" lay-filter="ew_tb_checkbox_zmn-table" ' + (d.checked ? 'checked' : '') + ' lay-skin="primary"/>' : '';
            }},
            {field: 'moduleId', title: '模块ID', width: 80, align: 'center', sort: false},
            {field: 'moduleName', title: '<div id="modualNameDiv" style="cursor: pointer"><span>模块名称</span><span class="ew-tree-table-arrow layui-icon"></span></div>', width: 240, sort: false, templet: function(d) {
                return d.level == 0 ? ('<b>' + d.moduleName + '</b>') : d.moduleName;
                }},
            {field: '', title: '权限列表', minWidth: 180, align: 'left', singleLine: false, templet: function(d) {
                let html = '';
                d.permits.forEach(function (item, i) {
                    html += '<input type="checkbox" name="permit" data-type="' + d.moduleId + '" value="' + item.permitId + '" ' + (item.checked ? 'checked' : '') + ' title="' + item.permitName + '" lay-skin="primary"/>'
                });
                return html;
            }}
        ]],
        reqData: function (data, callback) {     // 数据加载后回调
            $.get('/role/permit/ajaxTree.action?roleId=' + json.roleId, function (res) {
                if(res.status == 200) {
                    res.data.forEach(function(item) {
                        if(item.level <= 0) {
                            item.open = true;
                        }
                    });
                    callback(res.data)
                } else {
                    callback(res.message)
                };
            });
        },
        done:function () {
            $("#modualNameDiv").click(function () {
                let _this = $(this);
                if(_this.hasClass("ew-tree-table-open")){
                    _this.removeClass("ew-tree-table-open");
                    //还原为二级节点展开
                    insTb.reload();
                }else{
                    _this.addClass("ew-tree-table-open");
                    //展开所有叶子节点
                    insTb.expandAll();
                }
            });
        }
        // end: function(e){},
    });

    // 快速选择
    treeTable.on('checkbox(zmn-table)', function(obj) {
        let moduleId = obj.data.moduleId;
        let checked = obj.checked;

        // 所有会受影响的节点数据
        let childrenNodes = new Array();
        let $permits = $('input[data-type=' + moduleId + ']');
        if ($permits && $permits.length > 0) {
            childrenNodes.push($permits);
        }

        // 递归查询下级子节点
        let childrenPermits = obj.data.children;
        if (childrenPermits && childrenPermits.length > 0) {
            finalQuery(childrenNodes,childrenPermits)
        }

        if(childrenNodes.length==0){
            return;
        }

        childrenNodes.forEach(function (item,index) {
            let $this = $(item);
            $this.prop({checked: checked});
        });
        layui.form.render('checkbox');
    });

    // 分配权限
    treeTable.on("toolbar(zmn-table)", function (obj) {
        layui.layer.confirm('确认提交吗？', function () {
            let $ = layui.$;
            var $permitIds = $('input[name="permit"]');
            var permitIds = new Array();
            if ($permitIds.length > 0) {
                $permitIds.each(function (i) {
                    let $this = $(this);
                    if ($this.prop('checked')) {
                        permitIds.push($(this).val());
                    }
                });
            }
            if (permitIds == null || permitIds.length == 0) {
                layui.layer.msg("请选择要分配的权限");
                return;
            }
            zmnPage.ajaxSimple(zmnApp.SYS_BASE_URL + "/role/permit/modify/assign.action", {
                roleId: json.roleId,
                permitIds: permitIds.join(",")
            }, 1500);
        });
    });

    // 子节点递归
    function finalQuery(childNodeArr,childrenPermits) {
        for (let i = 0; i < childrenPermits.length; i++) {
            let currentNode = childrenPermits[i];
            function fun(currentNode) {
                let permits = currentNode.permits;
                if(permits && permits.length > 0){
                    for (let j = 0; j < permits.length; j++) {
                        let current = permits[j];
                        childNodeArr.push($('input[data-type=' + current['moduleId'] + ']'));
                    }
                }
                let children =  currentNode.children;
                if(children && children.length > 0){
                    for (let k = 0; k < children.length; k++) {
                        let current = children[k];
                        fun(current);
                    }
                }

            }
            fun(currentNode);
        }
    }

    // 快速选择
    // checkPermit = function(el, moduleId) {
    //     alert(moduleId);
    //     return;
    //     let $permits = $('input[data-type='+ moduleId +']');
    //     if(!$permits || $permits.length == 0) {
    //         return;
    //     }
    //     let checked = $(el).prop('checked');
    //     $permits.each(function (i) {
    //         $(this).prop('checked', checked);
    //     });
    // };

    //对外暴露的接口
    exports('role_permit_tree', {});
});